package meb

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"time"
	"vitepress-serve/internal/common/hgin"
	"vitepress-serve/internal/model"
)

// ProductList 产品列表
func (ctl *Controller) ProductList(ctx *gin.Context) (err error) {
	var (
		uid = hgin.CtxToken(ctx).Uid
		zf  = ctl.ConfigService.Wxpay()
	)

	var products []model.Product
	if err = ctl.db.Where("status = ?", model.ProductStatus_UP).Order("rank DESC").Find(&products).Error; err != nil {
		return
	}

	var items = make([]ProductListBodyItem, 0)
	for _, p := range products {
		items = append(items, ProductListBodyItem{
			ProdId:    p.ProdId,
			ProdName:  p.ProdName,
			UnitPrice: p.UnitPrice,
			MarkPrice: p.MarkPrice,
			BuyUrl:    fmt.Sprintf("%s%s?uid=%s&prod_id=%s", zf.SafeUrl, PATH_PRODUCT_BUY, uid, p.ProdId),
		})
	}

	// 根据uid缓存当前host，用于记录下单网站域名
	ctl.cache.Set(ctxHostKey+uid, ctx.Request.Host, 1*time.Hour)

	hgin.ApiRes(ctx, ProductListBody{
		Items: items,
	})
	return
}

const ctxHostKey = "ctx_host_uid_"

type ProductListArgs struct {
}

type ProductListBody struct {
	Items []ProductListBodyItem `json:"items"`
}

type ProductListBodyItem struct {
	ProdId    string `json:"prod_id"`
	ProdName  string `json:"prod_name"`
	UnitPrice uint64 `json:"unit_price"`
	MarkPrice uint64 `json:"mark_price"`
	Intro     string `json:"intro"`
	BuyUrl    string `json:"buy_url"` //购买链接，微信扫码可直接下单  示例：/vpapi/meb/product-buy?uid=xx&prod_id=xx
}
